import {
  getSaleTarget,
  editeSaleTarget
} from '../../api/sale'
import {
  SALE_TARGET_LIST,
  SALE_TARGET_CURRENT_ROW,
  SALE_TARGET_DATA_COUNT,
  SALE_TARGET_HISTORY_DATA,
  SALE_TARGET_UPLOAD_LIST
} from '../motations-type'

export default {
  state: {
    saleTargetList: [],
    saleTargetDataCount: null,
    pageSize: 20,
    saleTargetHistoryData: [],
    row: {
      uname: '',
      num: '',
      ctime: ''
    }
  },
  getters: {
    saleTargetList: state => state.saleTargetList
  },
  mutations: {
    [SALE_TARGET_LIST] (state, data) {
      state.saleTargetList = data
    },
    [SALE_TARGET_CURRENT_ROW] (state, data) {
      state.row = data
    },
    [SALE_TARGET_DATA_COUNT] (state, data) {
      state.saleTargetDataCount = data
    },
    [SALE_TARGET_HISTORY_DATA] (state, data) {
      state.saleTargetHistoryData = data
    },
    [SALE_TARGET_UPLOAD_LIST] (state, data) {
      state.saleTargetList = state.saleTargetList.push(data)
    }
  },
  actions: {
    async getSaleTargetList ({ commit, rootState }, playload) {
      let data = {}
      let newData = []
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      const resp = await getSaleTarget(data)
      resp.data.data.rows.map((item) => {
        newData = [...newData, {
          id: item.id,
          uname: item.uname ? item.uname : '-',
          num: item.num ? item.num : '-',
          ctime: item.ctime ? item.ctime : '-'
        }]
      })
      commit(SALE_TARGET_LIST, newData)
      commit(SALE_TARGET_DATA_COUNT, resp.data.data.total)
      if (newData.length < rootState.saleTarget.pageSize) {
        commit(SALE_TARGET_HISTORY_DATA, newData)
      } else {
        commit(SALE_TARGET_HISTORY_DATA, newData.slice(0, rootState.saleTarget.pageSize))
      }
    },
    async updateSaleTargetData ({ commit, rootState }, playload) {
      let data = {}
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      await editeSaleTarget(data)
    },
    async getSaleTargetCurrentRow ({ commit, rootState }, row) {
      commit(SALE_TARGET_CURRENT_ROW, row)
    },
    async changeSaleTargetPage ({ commit, rootState }, index) {
      let data = rootState.saleTarget.saleTargetList
      let _start = (index - 1) * rootState.saleTarget.pageSize
      let _end = index * rootState.saleTarget.pageSize
      commit(SALE_TARGET_HISTORY_DATA, data.slice(_start, _end))
    },
    async getSaleTargetUploadList ({ commit, rootState }, uploadList) {
      commit(SALE_TARGET_UPLOAD_LIST, uploadList)
    }
  }
}
